/** 读取文件并获取地址 */
export function readFileUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onload = function () {
      resolve(this.result as string)
    }

    reader.onerror = function (e) {
      reject(e)
    }
  })
}

/** base64ToFile */
export function base64ToFile(data: string, fileName = '') {
  const arr = data.split(',')
  const mime = arr[0]?.match(/:(.*?);/)?.[1]
  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }

  return new File([u8arr], fileName, { type: mime })
}
